//
//  GasConfirmVC.m
//  NtoccDriverNew
//
//  Created by niyongsheng on 2022/10/18.
//  Copyright © 2022 GCY. All rights reserved.
//

#import "GasConfirmVC.h"
#import "FFPopup.h"
#import "GasConfirmAlertView.h"

@interface GasConfirmVC ()
@property (weak, nonatomic) IBOutlet UILabel *textL1;
@property (weak, nonatomic) IBOutlet UILabel *textL2;
@property (weak, nonatomic) IBOutlet UILabel *textL3;
@property (weak, nonatomic) IBOutlet UILabel *textL4;
@property (weak, nonatomic) IBOutlet UILabel *textL5;
@property (weak, nonatomic) IBOutlet UILabel *textL6;

@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;

@property (strong, nonatomic) GasConfirmAlertView *confirmAlertV;
@property (strong, nonatomic) FFPopup *popup;

@property (assign, nonatomic) NSInteger secondCount;

@end

@implementation GasConfirmVC
// 循环定时器
static dispatch_source_t _timer;

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"加油确认";
    
    ViewRadius(_confirmBtn, 5)
    ViewBorderRadius(_cancelBtn, 5, 1, Theme_ColorValue)
    
    _textL1.text = _model.serialNo;
    _textL2.text = _model.totalPrice;
    _textL3.text = _model.stationName;
    _textL4.text = _model.oilType.integerValue == 1 ? @"汽油" : @"柴油";
    _textL5.text = _model.oilLabel;
    _textL6.text = _model.gmtCreated;
}

- (IBAction)confirmBtnOnclicked:(UIButton *)sender {
    NSString *urlStr = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl],GaspayOrderResult);
    NSDictionary *params = @{
        @"phone": self.model.driverPhone,
        @"serialNo": self.model.serialNo,
        @"payAmount": [NSString stringWithFormat:@"%.2f", self.model.totalPrice.floatValue/100],
        @"status": @1,
        @"payNo": @"ios pay no ...",
    };
    @weakify(self)
    [HTTPManager postNetworkRequest:urlStr
                      withParameter:params
                             withVC:[UIViewController new]
                            netName:@"加油确认"
                            success:^(id response, NSString *msg) {
        @strongify(self)
        [XSInfoView showInfo:@"已确认，等待支付结果" onView:self.view];
        sender.enabled = NO;
        [sender setBackgroundColor:[UIColor colorWithHexString:@"#E6E6E6"]];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self startCycleTimer:self.model.serialNo];
        });
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (IBAction)cancelBtnOnclicked:(UIButton *)sender {
    NSString *urlStr = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl],GasStationPayment);
    NSDictionary *params = @{
        @"code": self.model.code,
        @"transactionStatus": @4
    };
    @weakify(self)
    [HTTPManager putNetworkRequest:urlStr
                      withParameter:params
                             withVC:[UIViewController new]
                            netName:@"加油取消"
                            success:^(id response, NSString *msg) {
        @strongify(self)
        [XSInfoView showInfo:@"已取消" onView:self.view];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (void)selectPayResult:(NSString *)orderCode {
    self.secondCount += 5;
    if (self.secondCount >= 60*2) {
        self.confirmAlertV.isSuccess = NO;
        self.confirmAlertV.msg = @"获取支付结果超时！";
        [self.popup showWithLayout:FFPopupLayoutMake(FFPopupHorizontalLayout_Center, FFPopupVerticalLayout_Center)];
    }
    
    @weakify(self)
    NSString *urlStr = CJStringWithFormat(@"%@%@/%@",[NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], GasStationPayment,  orderCode);
    [HTTPManager getNetworkRequest:urlStr
                     withParameter:nil
                            withVC:self
                           netName:@"查询付款结果"
                           success:^(id response, NSString *msg) {
        @strongify(self)
        GasConfirmModel *model = [GasConfirmModel mj_objectWithKeyValues:response];
        if (model.transactionStatus.integerValue == 2) { // 2已付款
            self.confirmAlertV.isSuccess = YES;
            [self.popup showWithLayout:FFPopupLayoutMake(FFPopupHorizontalLayout_Center, FFPopupVerticalLayout_Center)];
            
        } else if (model.transactionStatus.integerValue == 4) { // 4已取消
            self.confirmAlertV.isSuccess = NO;
            [self.popup showWithLayout:FFPopupLayoutMake(FFPopupHorizontalLayout_Center, FFPopupVerticalLayout_Center)];
            
        } else {
            
        }
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (void)startCycleTimer:(NSString *)orderCode {
    NSTimeInterval second = 5;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 2 * NSEC_PER_SEC), second * NSEC_PER_SEC, 0);
    // 定时器触发事件
    dispatch_source_set_event_handler(_timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self selectPayResult:orderCode];
        });
    });

    dispatch_resume(_timer);
}

- (void)dealloc {
    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}

- (FFPopup *)popup {
    if (!_popup) {
        _popup = [FFPopup popupWithContentView:self.confirmAlertV showType:FFPopupShowType_GrowIn dismissType:FFPopupDismissType_ShrinkOut maskType:FFPopupMaskType_Dimmed dismissOnBackgroundTouch:NO dismissOnContentTouch:NO];
    }
    return _popup;
}

- (GasConfirmAlertView *)confirmAlertV {
    if (!_confirmAlertV) {
        CGFloat width = 300.0*ScreenW/375.0;
        CGFloat height = 240.0*ScreenW/375.0;
        _confirmAlertV = [[GasConfirmAlertView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
        @weakify(self)
        _confirmAlertV.block = ^(int index) {
            @strongify(self)
            [self.popup dismissAnimated:YES];
            [self.navigationController popToRootViewControllerAnimated:YES];
        };
    }
    return _confirmAlertV;
}

@end
